package com.github.permissiondog.cancanpbackend.servlet;

import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.response.UploadResourceResponse;
import com.github.permissiondog.cancanpbackend.service.ResourceService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/resource/*")
@MultipartConfig(maxFileSize = 10 * 1024 * 1024)
public class ResourceServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        var file = request.getPart("file");
        var data = file.getInputStream().readAllBytes();
        var sha = ResourceService.getInstance().createResource(data, file.getContentType());
        json(response, UploadResourceResponse.builder()
                .ok(true)
                .sha(sha)
                .length(data.length)
                .type(file.getContentType())
                .build());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        var sha = request.getRequestURI().substring(request.getRequestURI().lastIndexOf('/') + 1);
        var file = ResourceService.getInstance().getResource(sha);
        if (file == null) {
            response.setStatus(404);
            return;
        }
        response.setContentType(file.getType());
        response.getOutputStream().write(file.getData());
    }
}
